package cn.helios.framework.scheduler.service.impl;

import cn.helios.framework.scheduler.dao.ScheduleTaskMapper;
import cn.helios.framework.scheduler.entity.ScheduleTask;
import cn.helios.framework.scheduler.manager.SchedulerJobService;
import cn.helios.framework.scheduler.service.SchedulerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author chenshiwen@ibabygroup.cn
 * @date 2017-10-20 14:04
 **/
@Slf4j
@Service
public class SchedulerServiceImpl implements SchedulerService {

    @Resource
    private ScheduleTaskMapper scheduleTaskMapper;

    @Resource
    private SchedulerJobService schedulerJobService;

    @Override
    @Transactional
    public void addTask(ScheduleTask task) {
        if (task == null) {
            log.info("任务信息不能为空");
            return;
        }
        task.setId(getId());
        task.setCreateTime(new Date());
        if (task.getStatus() == null) {
            task.setStatus(4);
        }
        int save = scheduleTaskMapper.save(task);
        if (save != 0 && task.getStatus() == 1) {
            schedulerJobService.addTask(task);
        }
    }

    @Override
    @Transactional
    public void delTask(String id) {
        int modify = scheduleTaskMapper.modifyStatus(id, 4, "");
        if (modify != 0) {
            schedulerJobService.deleteJob(id);
        }
    }

    @Override
    @Transactional
    public void modifyTask(ScheduleTask task) {
        if (task == null || StringUtils.isEmpty(task.getId())) {
            log.info("任务信息，或者任务id不能为空");
            return;
        }
        schedulerJobService.modifyJob(task.getId(), task.getCronExpression());
        scheduleTaskMapper.modifyTask(task);
    }
}
